<?php

require_once dirname(__FILE__) . '/../lib/clientGeneratorConfiguration.class.php';
require_once dirname(__FILE__) . '/../lib/clientGeneratorHelper.class.php';

/**
 * client actions.
 *
 * @package    smp-crm
 * @subpackage client
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class clientActions extends autoClientActions {

    public function executeIndex(sfWebRequest $request) {
        // sorting  
        if ($request->getParameter('sort') && $this->isValidSortColumn($request->getParameter('sort'))) {
            $this->setSort(array($request->getParameter('sort'), $request->getParameter('sort_type')));
        }

        // pager
        if ($request->getParameter('page')) {
            $this->setPage($request->getParameter('page'));
        }

        $this->pager = $this->getPager();
        $this->sort = $this->getSort();
    }

    protected function addSortQuery($query) {
        $list_sort = $this->getSort();
        if (empty($list_sort)) {
            return;
        }

        foreach ($list_sort as $sort) {
            $query->addOrderBy($sort[0] . ' ' . $sort[1]);
        }
    }

    protected function getSort() {
        $sort = $this->getUser()->getAttribute('client.sort', array(), 'admin_module');

        if (!empty($sort)) {
            return $sort;
        }

        $this->setSort($this->configuration->getDefaultSort());

        return $this->getUser()->getAttribute('client.sort', array(), 'admin_module');
    }

    protected function setSort(array $sort) {

        if (null !== $sort[0] && null === $sort[1]) {
            $sort[1] = 'asc';
        }

        $list_sort = $this->getUser()->getAttribute('client.sort', array(), 'admin_module');
        $exist = false;

        // If the sort already exists update the sort type
        foreach ($list_sort as $key => $sort_exist) {

            if ($sort_exist[0] == $sort[0]) {
                $list_sort[$key][1] = $sort[1];
                $exist = true;
                break;
            }
        }
        // if the sort no exists add to the list
        if (!$exist && $sort[0] !== null && $sort[1] !== null) {
            $list_sort[$sort[0]] = $sort;
        }

        $this->getUser()->setAttribute('client.sort', $list_sort, 'admin_module');
    }

    public function executeListView(sfWebRequest $request) {
        $client = $this->getRoute()->getObject();
        $this->redirect( 'suivi-contact/profil?user-id=' . $client->getId());
    }

}
